package com.yunduansing.demo.service.impl;

import com.yunduansing.demo.dao.account.AccountDao;
import com.yunduansing.demo.mapper.UserRoleMapper;
import com.yunduansing.demo.model.account.LoginModel;
import com.yunduansing.demo.model.account.LoginUserModel;
import com.yunduansing.demo.model.common.CacheKeyPrefix;
import com.yunduansing.demo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao dao;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private final String CACHE_KEY_PREFIX=CacheKeyPrefix.LOGIN_USER;
    @Value("${login.user.expires}")
    private long cacheExpireTime;

    @Override
    public boolean login(LoginModel model) {
        var result=dao.findByAccountAndPassword(model.getAccount(),model.getPassword());
        return result;
    }

    @Override
    public LoginUserModel login(String account) {
        var cache=redisTemplate.opsForValue().get(CACHE_KEY_PREFIX+account);
        if(cache!=null) return (LoginUserModel)cache;
        var user= dao.findByAccount(account);
        List<String> roles=new ArrayList<>();
        if(user!=null) {
            var userRoles=userRoleMapper.findRolesByUser(user.getId());
            if(userRoles.size()>0){
                for(var item:userRoles){
                    roles.add(item.getRoleCode());
                }
            }
        }
        var loginUser=new LoginUserModel(user,roles);
        redisTemplate.opsForValue().set(CACHE_KEY_PREFIX+account, loginUser,cacheExpireTime,TimeUnit.MILLISECONDS);
        return loginUser;
    }
}
